package com.cloudwise.gproject.controller;

import com.cloudwise.gproject.entity.Role;
import com.cloudwise.gproject.entity.User;
import com.cloudwise.gproject.entity.UserRole;
import com.cloudwise.gproject.service.*;
import com.cloudwise.gproject.util.Result;
import com.cloudwise.gproject.util.ReturnStatus;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户信息表(User)表控制层
 *
 * @author makejava
 * @since 2021-03-17 18:48:00
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RoleService roleService;
    @Resource
    private HttpSession session;
    @Resource
    private CommonFileService commonFileService;

    @RequestMapping("toHomepage")
    public String toHomepage() {
        User user = (User)session.getAttribute("userInfo");
        session.setAttribute("UserInfo", user);
        return "/back/homepage";
    }

    /**
     * @param user:
     * @return com.cloudwise.trademark.entity.ReturnBean
     * @create by: IvanZ
     * @description : 修改密码
     * @create time: 2020/12/18 18:42
     */
    @PutMapping("updatePassword")
    public Result updatePassword(User user) {
        return new Result(ReturnStatus.SUCCESS.getCode(),
                ReturnStatus.SUCCESS.getMessage(), 0, userService.update(user));
    }

    /**
     * 用户名查重
     *
     * @param loginName 用户名
     * @return boolean
     * @createTime 2020/12/29 23:11
     */
    @GetMapping("/checkLoginName")
    public String checkLoginName(String loginName) {
        //根据登录名查询用户(用户名不能重复)
        User userTemp = userService.queryByLoginName(loginName);
        //如果用户不为空，返回错误
        if (userTemp != null) {
            return "false";
        }
        return "true";
    }

    /**
     * 查询用户对应的角色id
     *
     * @param userId 主键
     * @return List<Integer>
     * @createBy Enzo
     * @createTime 2020/12/29 23:12
     */
    @GetMapping("findSelectRole")
    public List<Integer> findSelectRole(int userId) {
        List<Integer> list = new ArrayList<>();
        List<UserRole> userRoleList = userRoleService.queryById(userId);
        for (UserRole userRole : userRoleList) {
            list.add(userRole.getRoleId());
        }
        return list;
    }

    /**
     * 头像上传
     *
     * @param headPic
     * @return
     */
    @ResponseBody
    @RequestMapping("uploadHeadPic")
    public Result uploadHeadPic(@RequestParam MultipartFile headPic) {
        return new Result(ReturnStatus.SUCCESS.getCode(),
                ReturnStatus.SUCCESS.getMessage(), 0,
                this.commonFileService.uploadFile(headPic, "files/user/images"));
    }

    @ResponseBody
    @PostMapping("insert")
    public Result insert(User user) {
        /*System.out.print("================");
        System.out.println(user.toString());
        System.out.print("部门："+user.getDeptId());
        System.out.println("================");*/

        User user1 = userService.queryByLoginName(user.getLoginName());
        //如果用户不为空，返回错误
        if (user1 != null) {
            return new Result(ReturnStatus.FAIL.getCode(), ReturnStatus.FAIL.getMessage(),
                    0, user1);
        }
        //设置删除标志
        user.setDelFlag("0");
        //添加用户信息
        User user2 = userService.insert(user);
        //添加userRole信息
        userRoleService.insert(user);

        return new Result(ReturnStatus.SUCCESS.getCode(), ReturnStatus.SUCCESS.getMessage(),
                0, user2);
    }

    /**
     * @param  
     * @return  
     * @create by: 卫子健
     * @description: 更新单个数据 
     * @create time: 2021/3/19 21:44
     */
    @ResponseBody
    @PutMapping("update")
    public Result update(User user, HttpSession session) {
        //获取当前用户的用户名即为 执行了更新操作的人
        User userInfo = (User)session.getAttribute("userInfo");
        user.setUpdateBy(userInfo.getUserName());

        //删除所有该userId下的userRole
        userRoleService.deleteById(user.getUserId());
        //再添加该user至userRole表
        userRoleService.insert(user);

        return new Result(ReturnStatus.SUCCESS.getCode(), ReturnStatus.SUCCESS.getMessage(),
                0, userService.update(user));
    }

    /**
     * @param  
     * @return  
     * @create by: 卫子健
     * @description: 根据id删除部门 
     * @create time: 2021/3/19 20:57
     */
    @ResponseBody
    @RequestMapping("deleteById")
    public Result deleteById(Integer userId) {
        boolean b = userService.deleteById(userId);
        userRoleService.deleteById(userId);
        return new Result(ReturnStatus.SUCCESS.getCode(), ReturnStatus.SUCCESS.getMessage(),
                0, b);
    }

    /**
     * @param userIds 
     * @return  
     * @create by: 卫子健
     * @description: 删除多个id对应的数据 
     * @create time: 2021/3/19 23:21
     */
    @ResponseBody
    @RequestMapping("deleteByIds")
    public Result deleteByIds(String userIds) {
        int i = userService.deleteByIds(userIds);
        return new Result(ReturnStatus.SUCCESS.getCode(), ReturnStatus.SUCCESS.getMessage(),
                0, i);
    }

    /**
     * @param page
     * @param limit
     * @param user 
     * @return com.cloudwise.trademark.util.Result 
     * @create by: 卫子健
     * @description: 分页条件查询所有部门列表 
     * @create time: 2021/3/19 20:35
     */
    @ResponseBody
    @RequestMapping("queryAll")
    public Result queryAll(Integer page, Integer limit, User user) {
        PageInfo pageInfo = userService.queryAll(page, limit, user);
        return new Result(ReturnStatus.SUCCESS.getCode(), ReturnStatus.SUCCESS.getMessage(),
                pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ResponseBody
    @RequestMapping("selectOne")
    public User selectOne(Integer id) {
        return this.userService.queryById(id);
    }

    /**
     * @param  
     * @return java.lang.String 
     * @create by: 卫子健
     * @description: 跳转到登录页面, login.html 
     * @create time: 2021/3/18 18:43
     */
    @RequestMapping("toLogin")
    public String toLogin() {
        return "/back/login2";
    }

    /**
     *  
     *
     * @param user 
     * @return java.lang.String 
     * @create by: 卫子健
     * @description: 登录验证 
     * @create time: 2021/3/18 18:45
     */
    @RequestMapping("login")
    public String login(User user, Model model,HttpServletRequest request) {
        //收集用户信息
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getLoginName(), user.getPassword());
        //获取当前登录用户对象
        Subject subject = SecurityUtils.getSubject();
        try {
            //登录
            subject.login(usernamePasswordToken);
            HttpSession session = request.getSession();
            //把用户信息放入session
            User userInfo = (User) subject.getPrincipal();
            session.setAttribute("userInfo", userInfo);
            session.setAttribute("username", userInfo.getLoginName());
            return "redirect:/menu/toMenu";
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        model.addAttribute("errorInfo", "用户名或密码错误！");
        return "/back/login2";
    }

    /**
     * @param  
     * @return  
     * @create by: 卫子健
     * @description: 跳转到部门管理页面user.html 
     * @create time: 2021/3/19 19:45
     */
    @RequestMapping("toUser")
    public String toUser() {
        List<Role> roles = roleService.queryAllWithoutLimit(new Role());
        session.setAttribute("roleList", roles);
        return "/back/user";
    }

    /**
     * @param :
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @create by: IvanZ
     * @description : 查询所有角色
     * @create time: 2020/12/17 19:53
     */
    @ResponseBody
    @RequestMapping("findAllRole")
    public List<Map<String, Object>> findAllRole() {

        List<Map<String, Object>> allRole = userService.findAllRole();
        System.out.print("============findAllRole===========");
        for (Map<String, Object> stringObjectMap : allRole) {
            System.out.print(" "+stringObjectMap.get("role_name"));;
        }
        System.out.print("============findAllRole===========");
        return allRole;
    }
}
